package com.zang.netty.nettydecoder;

import com.zang.netty.io.model.enums.SocketEnum;
import com.zang.netty.nettyio.server.TimeServerHandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author Zhang Qiang
 * @Date 2019/7/20 18:29
 */
public class TimeServerByDecoder {

    public void bind(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup wordGroup = new NioEventLoopGroup();

        try{

            ServerBootstrap b = new ServerBootstrap();

            b.group(bossGroup, wordGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChildChannelHandler());

            // 绑定端口，同步等待成功
            ChannelFuture future = b.bind(port).sync();

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();


        }finally {

            // 优雅推出
            bossGroup.shutdownGracefully();
            wordGroup.shutdownGracefully();
            System.out.println(" 优雅退出");

        }


    }

}

class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
        socketChannel.pipeline().addLast(new StringDecoder());
        socketChannel.pipeline().addLast(new TimeServerHandle());
    }

    public static void main(String[] args) throws InterruptedException {
        int port = SocketEnum.PORT.getNum();
        if (args!= null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e){}
        }

        new TimeServerByDecoder().bind(port);

    }


}
